<template>
  <div>
    <div class="choose-department">
      <scroller :scrollbar-x="false" lock-y class="scoller-box depart-box">
        <div :style="{ width: departScrollerWidth }" class="member-box">
          <div
            v-for="(item, index) in departmentList"
            :key="index"
            class="depart-content"
            @click="chooseOrg(item, index, 0)"
          >
            <p
              :class="item.isActiveColor ? 'activeColor' : ''"
              class="org-name"
            >
              {{ item.orgName }}
            </p>
            <div class="arrow-right">
              <x-icon type="ios-arrow-forward" size="20" />
            </div>
            <div class="clearfix" />
          </div>
          <div class="clearfix" />
        </div>
      </scroller>
    </div>

    <div class="dep-friend-list">
      <mescroll-vue
        ref="mescroll"
        :down="mescrollDown"
        :up="mescrollUp"
        @init="mescrollInit"
      >
        <div
          v-for="(item, index) in departList"
          :key="index"
          class="content"
          @click.stop="chooseOrg(item, index, 1)"
        >
          <img class="personal-img" src="@/assets/notice/f.png" >
          <p class="personal-name">{{ item.orgName }}</p>
          <div @click.stop="addOrg(item)">
            <x-icon
              v-show="isSelectedOrg(item, 'department')"
              type="ios-checkmark"
              class="select-btn"
              size="24"
            />
            <x-icon
              v-show="!isSelectedOrg(item, 'department')"
              type="ios-circle-outline"
              class="select-btn"
              size="24"
            />
          </div>

          <div class="clearfix" />
        </div>

        <div
          v-for="item in membersList"
          :key="item.sourceId"
          class="content"
        >
          <img :src="item.portraitUrl" :onerror="errorDefaultImg" class="personal-img" >
          <p class="personal-name">{{ item.displayName }}</p>
          <div @click="addOrgMember(item)">
            <x-icon
              v-show="isSelectedOrg(item, 'member')"
              type="ios-checkmark"
              class="select-btn"
              size="24"
            />
            <x-icon
              v-show="!isSelectedOrg(item, 'member')"
              type="ios-circle-outline"
              class="select-btn"
              size="24"
            />
          </div>
          <div class="clearfix" />
        </div>
      </mescroll-vue>
    </div>
  </div>
</template>

<script>
import { Scroller, Toast } from 'vux';
import { getOrgnation, getOrgFriend } from '@/api/dood';
import MescrollVue from 'mescroll.js/mescroll.vue';
import { mescroll } from '@/common/minxins';

export default {
  name: 'Orgnization',
  components: {
    Scroller,
    Toast,
    MescrollVue,
  },
  mixins: [mescroll],
  data() {
    return {
      departmentList: [], // 部门列表
      departList: [], // 子部门列表
      membersList: [], // 部门下成员列表
      activeColor: 'activeColor',
      departScrollerWidth: 375 + 'px', // 部门列表展示滚动宽度
      noMoreData: false,
      indexOrgId: '', // 当前的组织ID
      areaDepartment: [], // 存储已选择的所有部门
      areaOrgMemberList: [], // 存储部门下已选择的所有人员
      checkedOrgs: [], // 需要传递给后端选中的组织
      uncheckedOrgs: [], // 需要传递给后端取消选中的组织
      checkedUsers: [], // 需要传递给后端选中的人
      uncheckedUsers: [], // 需要传递给后端取消选中的人
      totalPage: 0,
      page: 1,
      size: 20,
      remak: '', // 父组织部门， 用于部门下的好友分页
      type: '', // 父组织部门有没有被选中， 用于部门下的好友分页
      errorDefaultImg: `this.src="${require('@/assets/notice/defaultError.png')}"`,
    };
  },
  created() {
    this.getOrgnations('', '');
  },
  methods: {
    getOrgnations(parentOrgId, remark) {
      Promise.all([
        // FIXME(ZK) 第三方平台id暂时写死豆豆平台1
        getOrgnation({
          thirdPartyId: '1',
          parentOrgId: parentOrgId,
        }),
        getOrgFriend({
          orgId: parentOrgId,
          page: this.page,
          size: this.size,
        }),
      ]).then(res => {
        this.initOrgnations(parentOrgId, remark, res[0], res[1]);
      });
    },
    // 获取组织架构
    async initOrgnations(parentOrgId, remark, result, friendRes) {
      // 处理根组织的数据
      if (!parentOrgId) {
        this.departmentList = [];
        const rootOrg = {};
        rootOrg.orgId = result.data[0].orgId;
        rootOrg.orgName = result.data[0].orgName;
        rootOrg.remark = result.data[0].remark;
        rootOrg.isActiveColor = true;
        this.departmentList.push(rootOrg);
        this.indexOrgId = this.departmentList[0].orgId;
        this.getOrgnations(this.indexOrgId, rootOrg.remark);
        return;
      }
      // 处理子组织
      this.initPageParams();
      const selectFlag = this.isSameDepart(
        parentOrgId,
        this.areaDepartment,
        'orgId'
      );
      if (selectFlag) {
        result.data.forEach((items, index) => {
          const isSelect = this.isSameDepart(
            items.orgId,
            this.areaDepartment,
            'orgId'
          );
          if (!isSelect) {
            this.areaDepartment.push(items);
          }
        });
        if (this.uncheckedOrgs.length) {
          this.uncheckedOrgs.forEach((item, index) => {
            this.areaDepartment = this.areaDepartment.filter(
              data => item.orgId !== data.orgId
            );
          });
        }
        // 选中部门去获取部门下的好友，且好友需要全部被选中
        this.getOrgFriends(parentOrgId, remark, 'select', friendRes);
      } else {
        // 如果当前机构没有被选中，它和它的子组织都需要取消选中
        if (this.areaDepartment.length) {
          result.data.forEach(item => {
            this.areaDepartment = this.areaDepartment.filter(
              data => item.orgId !== data.orgId
            );
          });
          if (this.checkedOrgs.length) {
            this.checkedOrgs.forEach((item, index) => {
              const iSExist = this.isSameDepart(
                item.orgId,
                this.areaDepartment,
                'orgId'
              );
              if (!iSExist) {
                this.areaDepartment.push(item);
              }
            });
          }
        }
        // 取消选中部门去获取部门下的好友，且好友需要全部被选中
        this.getOrgFriends(parentOrgId, remark, 'unselect', friendRes);
      }
      // 每次点击初始化分页插件
      this.mescroll.resetUpScroll();
      this.departList = result.data;
    },
    // 获取组织下的好友
    async getOrgFriends(id, remark, type, result) {
      this.remak = remark;
      this.type = type;
      if (result.data.length) {
        this.totalPage = Number(result.headers['x-total-page']);
        if (this.page === 1) {
          this.membersList = result.data;
        } else {
          this.membersList.push(...result.data);
        }
        this.membersList.forEach(item => {
          item.remark = remark;
          item.portraitUrl = item.portraitUrl || '';
          if (type === 'select') {
            const isSelect = this.isSameDepart(
              item.sourceId,
              this.areaOrgMemberList,
              'sourceId'
            );
            if (!isSelect) {
              this.areaOrgMemberList.push(item);
            }
            if (this.uncheckedUsers.length) {
              this.uncheckedUsers.forEach((item, index) => {
                this.areaOrgMemberList = this.areaOrgMemberList.filter(
                  data => item.sourceId !== data.sourceId
                );
              });
            }
          } else {
            this.areaOrgMemberList = this.areaOrgMemberList.filter(
              data => item.sourceId !== data.sourceId
            );
            // 如果checkedUsers中有值，对应的人应该被勾选中
            if (this.checkedUsers.length) {
              this.checkedUsers.forEach((item, index) => {
                const iSExist = this.isSameDepart(
                  item.sourceId,
                  this.areaDepartment,
                  'sourceId'
                );
                if (!iSExist) {
                  this.areaOrgMemberList.push(item);
                }
              });
            }
          }
        });
      } else {
        this.membersList = [];
      }
      this.$nextTick(() => {
        this.mescroll.endSuccess(result.data.length);
      });
    },
    // 判断当前数组存不存在相同元素
    isSameDepart(id, arr, type) {
      let flag = false;
      for (let i = 0; i < arr.length; i++) {
        if (id === arr[i][type]) {
          flag = true;
          break;
        }
      }
      return flag;
    },
    // 选择子组织去查询子组织中的子组织
    chooseOrg(item, index, n) {
      let isAddDepart = true; // 判断是否往部门列表里添加该组织
      this.indexOrgId = item.orgId;
      this.getOrgnations(this.indexOrgId, item.remark); // 获取子组织下的列表
      this.departmentList.forEach(data => {
        data.isActiveColor = false;
        if (item.orgId === data.orgId) {
          item.isActiveColor = true;
          isAddDepart = false;
        }
      });
      if (isAddDepart) {
        item.isActiveColor = true;
        this.departmentList.push(item);
      }
      if (this.departmentList.length > 1 && n === 0) {
        // 0---代表从头部选择组织 1---从列表去选择组织
        // 在头部选择某一个组织后，把该组织之后的组织给删除
        this.departmentList.splice(
          index + 1,
          this.departmentList.length - (index + 1)
        );
        this.departmentList[index].isActiveColor = true;
      }
      this.departScrollerWidth =
        375 + (this.departmentList.length - 1) * 100 + 'px'; // 动态设置部门滚动的位置
    },
    // 点击添加组织机构
    addOrg(item) {
      for (let i = 0; i < this.areaDepartment.length; i++) {
        if (item.orgId === this.areaDepartment[i].orgId) {
          this.areaDepartment.splice(i, 1);
          this.checkedOrgs = this.checkedOrgs.filter(
            data =>
              item.orgId !== data.orgId &&
              data.remark.indexOf(item.remark) <= -1
          );
          this.checkedUsers = this.checkedUsers.filter(
            data => data.remark.indexOf(item.remark) <= -1
          );
          this.areaOrgMemberList = this.areaOrgMemberList.filter(
            data => data.remark.indexOf(item.remark) <= -1
          );
          const isUnSelect = this.isSameDepart(
            item.orgId,
            this.uncheckedOrgs,
            'orgId'
          );
          if (!isUnSelect) {
            this.uncheckedOrgs.push(item);
          }
          this.selectedInfo();
          return;
        }
      }
      // 如果选中的org取消后再次选中，则需要从unCheckedOrgs中移除该部门
      if (this.uncheckedOrgs.length) {
        this.uncheckedOrgs = this.uncheckedOrgs.filter(
          data =>
            item.orgId !== data.orgId && data.remark.indexOf(item.remark) <= -1
        );
      }
      this.checkedOrgs.push(item);
      this.areaDepartment.push(item);
      this.selectedInfo();
    },
    // 点击组织机构下的人
    addOrgMember(item) {
      for (let i = 0; i < this.areaOrgMemberList.length; i++) {
        if (item.sourceId === this.areaOrgMemberList[i].sourceId) {
          this.areaOrgMemberList.splice(i, 1);
          this.checkedUsers = this.checkedUsers.filter(
            data => item.sourceId !== data.sourceId
          );
          const isUnSelect = this.isSameDepart(
            item.sourceId,
            this.uncheckedUsers,
            'sourceId'
          );
          if (!isUnSelect) {
            this.uncheckedUsers.push(item);
          }
          this.selectedInfo();
          return;
        }
      }
      // 如果选中的org取消后再次选中，则需要从unCheckedOrgs中移除该部门
      if (this.uncheckedUsers.length) {
        this.uncheckedUsers = this.uncheckedUsers.filter(
          data => item.sourceId !== data.sourceId
        );
      }
      this.checkedUsers.push(item);
      this.areaOrgMemberList.push(item);
      this.selectedInfo();
    },
    // 将选择后的组织和部门传递给父组件
    selectedInfo() {
      const selectedOrgInfo = {
        checkedOrgs: this.checkedOrgs,
        uncheckedOrgs: this.uncheckedOrgs,
        checkedUsers: this.checkedUsers,
        uncheckedUsers: this.uncheckedUsers,
      };
      this.$emit('getSelectOrgsAndUsers', selectedOrgInfo);
    },
    // 是否选中部门
    isSelectedOrg(item, type) {
      if (type === 'department') {
        for (let i = 0; i < this.areaDepartment.length; i++) {
          if (item.orgId === this.areaDepartment[i].orgId) {
            return true;
          }
        }
        return false;
      } else {
        for (let i = 0; i < this.areaOrgMemberList.length; i++) {
          if (item.sourceId === this.areaOrgMemberList[i].sourceId) {
            return true;
          }
        }
        return false;
      }
    },
    // 初始化分页参数
    initPageParams() {
      this.membersList = [];
      this.page = 1;
      this.totalPage = 0;
      this.mescrollUp.page.num = 0;
    },
    upCallback(page, mescroll) {
      this.page = page.num;
      const noMoreData = this.page > this.totalPage;
      if (!noMoreData) {
        getOrgFriend({
          orgId: this.indexOrgId,
          page: this.page,
          size: this.size,
        }).then(res => {
          this.getOrgFriends(this.indexOrgId, this.remak, this.type, res);
        });
      } else {
        this.$nextTick(() => {
          this.mescroll.endSuccess(this.membersList.length);
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
@import '../../common/css/address-book.less';
.mescroll {
  position: absolute;
  top: 160px;
  bottom: 0;
  height: auto;
}
</style>
